// 云函数入口文件
const cloud = require('wx-server-sdk')
const tcbRouter = require('tcb-router')
cloud.init()
const db = cloud.database()
const MAX_LIMIT_COUNT = 100
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new tcbRouter({
    event
  });
  app.router('bloglist',async(ctx,next)=>{
     keyword = event.keyword;
     let w = {}
     if(keyword.trim() !=""){
      w ={
        content:db.RegExp({
          regexp:keyword,
          options:'i'
        })
      }
     }
    let  bloglist = await db.collection('blog')
          .where(w)
          .skip(event.start)
          .limit(event.count)
          .orderBy('createTime','desc')
          .get()
          .then((res)=>{
            console.log(res);
            return res.data
          })
        ctx.body = bloglist
  })
  app.router('detail',async(ctx,next)=>{
    let detail= await db.collection('blog').where({
      _id:event.blogId
    }).get().then(res=>{
       return res.data
    })
    let countResult = await db.collection('blog_comment').count();
    let total = countResult.total;
    commentlist={
      data:[]
    }
      if(total>0){
        let betchTime = Math.ceil(total/MAX_LIMIT_COUNT)
        let tasks=[]
        for(let i = 0; i<betchTime;i++){
            let promise = await db.collection('blog_comment')
            .skip(i*MAX_LIMIT_COUNT)
            .limit(MAX_LIMIT_COUNT)
            .where({
              blogId:event.blogId
            })
            .orderBy('createTime','desc')
            .get()
            tasks.push(promise)
        }
       if(tasks.length>0){
        commentlist = (await Promise.all(tasks)).reduce((acc,cur)=>{
          return {
            data:acc.data.concat(cur.data)
          }
        })
       }
      }
    ctx.body = {
      detail,
      commentlist
    };
    
  })
  const wxContext = cloud.getWXContext()
  app.router('getBlogListByOpenid',async(ctx,next)=>{
    ctx.body = await db.collection('blog').where({
      _openid:wxContext.OPENID
    }).skip(event.start).limit(event.count)
    .orderBy('createTime','desc').get().then(res=>{
      return res.data
    })
  })
  return app.serve()
}